
<template>
  <view class="detail-page">
    <!-- 顶部导航 -->
    <view class="header">
      <text class="title">{{ caseInfo.sbTitle || '案例详情' }}</text>
    </view>
    <!-- 图片轮播 -->
    <swiper class="image-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500">
      <swiper-item v-for="(image, index) in bannerImages" :key="index">
        <image :src="image" class="swiper-image" mode="aspectFill" @tap="openImageGallery(index)"></image>
      </swiper-item>
    </swiper>
    <!-- 全屏图片画廊弹窗 -->
    <view v-if="showGallery" class="gallery-overlay" @tap="closeGallery">
      <view class="gallery-container" @tap.stop.prevent>
        <!-- 全屏图片容器 -->
        <view class="gallery-fullscreen"
              @touchstart="handleTouchStart"
              @touchmove="handleTouchMove"
              @touchend="handleTouchEnd">
          <image
              :src="currentImage"
              class="gallery-image"
              :style="imageStyle"
              mode="aspectFit"
              @tap.stop.prevent="handleImageTap"
          ></image>
        </view>

        <!-- 顶部信息栏 -->
        <view class="gallery-header">
          <text class="gallery-index" v-if="gallerySource === 'case'">{{ currentImageIndex + 1 }}/{{ bannerImages.length }}</text>
          <text class="gallery-index" v-else>{{ currentRoomImageIndex + 1 }}/{{ getCurrentRoomImagesLength() }}</text>
          <view class="gallery-actions">
            <text class="gallery-action" @tap="resetTransform">重置</text>
            <text class="gallery-close" @tap="closeGallery">✕</text>
          </view>
        </view>

        <!-- 底部指示器 -->
        <view class="gallery-footer">
          <view class="gallery-dots">
            <view
                v-for="(image, index) in (gallerySource === 'case' ? bannerImages : getCurrentRoomImages())"
                :key="index"
                class="gallery-dot"
                :class="{ active: (gallerySource === 'case' ? currentImageIndex === index : currentRoomImageIndex === index) }"
                @tap="switchImage(index)">
            </view>
          </view>
        </view>

        <!-- 左右切换箭头 -->
        <view v-if="(gallerySource === 'case' && bannerImages.length > 1) || (gallerySource === 'room' && getCurrentRoomImagesLength() > 1)" class="gallery-arrows">
          <text class="gallery-arrow gallery-arrow-left" @tap="prevImage" :class="{ disabled: (gallerySource === 'case' ? currentImageIndex === 0 : currentRoomImageIndex === 0) }">‹</text>
          <text class="gallery-arrow gallery-arrow-right" @tap="nextImage" :class="{ disabled: (gallerySource === 'case' ? currentImageIndex === bannerImages.length - 1 : currentRoomImageIndex === getCurrentRoomImagesLength() - 1) }">›</text>
        </view>
      </view>
    </view>

    <!-- 基本信息 -->
    <view class="info-section">
      <!-- 标签 -->
      <view class="tags">
        <text class="tag">{{ caseInfo.houseAreaDesc}}</text>
        <text class="tag">{{ caseInfo.houseTypeDesc }}</text>
        <text class="tag">{{ caseInfo.houseStyleDesc}}</text>
        <text class="tag">{{ caseInfo.houseBudgetDesc }}</text>
      </view>

      <view class="details-grid">
        <view class="detail-item">
          <text class="label">户型：</text>
          <text class="value">{{ caseInfo.houseTypeDesc }}</text>
        </view>
        <view class="detail-item">
          <text class="label">面积：</text>
          <text class="value">{{ caseInfo.houseAreaDesc }}</text>
        </view>
        <view class="detail-item">
          <text class="label">预算：</text>
          <text class="value">{{ caseInfo.houseBudgetDesc }}</text>
        </view>
        <view class="detail-item">
          <text class="label">地区：</text>
          <text class="value">{{ caseInfo.houseRegion }}</text>
        </view>
        <view class="detail-item">
          <text class="label">风格：</text>
          <text class="value">{{ caseInfo.houseStyleDesc }}</text>
        </view>
      </view>
    </view>

    <!-- 设计思路 -->
    <view class="design-thought">
      <view class="section-title">设计思路</view>
      <view class="content-wrapper">
        <text class="content">{{ caseInfo.houseDesign }}</text>
      </view>
    </view>

    <!-- 房间列表 -->
    <view class="room-list">
      <view class="room-item" v-for="(room, index) in roomList" :key="index">
        <view class="room-title">{{ room.sbTitle }}</view>
        <view class="room-desc">{{ room.sbiDesc }}</view>
        <!-- 展示所有图片 -->
        <view class="room-images">
          <image
              v-for="(img, imgIndex) in getRoomImages(room.sbiImgs)"
              :key="imgIndex"
              :src="img"
              class="room-image"
              mode="widthFix"
              @tap="openRoomImageGallery(index, imgIndex)">
          </image>
        </view>
      </view>
    </view>
    <view class="room-list" style="height:200rpx">
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="action-group">
        <view class="action-item">
          <text class="icon">
            <image
                :src="isFavorite ? '/static/icon/已收藏.png' : '/static/icon/未收藏.png'"
                class="favorite-icon"
                @tap="toggleFavorite"
            ></image>
          </text>
        </view>
      </view>
      <view class="button-group">
        <button class="contact-btn" @tap="contactDesigner">
          <text class="btn-text">一键联系设计师</text>
        </button>
      </view>
    </view>

  </view>
</template>

<style lang="scss">.detail-page {
  background-color: #f8f9fa;
  min-height: 60vh;
}

.header {
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eaeaea;
  .title {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
  }
}

.image-swiper {
  height: 400rpx;
  .swiper-image {
    width: 100%;
    height: 100%;
  }
}

.info-section {
  background-color: #fff;
  padding: 30rpx;
  margin-top: 20rpx;

  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-bottom: 30rpx;
    .tag {
      font-size: 24rpx;
      color: #666;
      background-color: #f0f0f0;
      padding: 8rpx 16rpx;
      border-radius: 8rpx;
    }
  }

  .details-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24rpx;
    .detail-item {
      display: flex;
      .label {
        font-size: 26rpx;
        color: #999;
        width: 80rpx;
        flex-shrink: 0;
      }
      .value {
        font-size: 26rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
}

.design-thought {
  background-color: #fff;
  padding: 30rpx;
  margin-top: 20rpx;
  .section-title {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 30rpx;
  }
  .content-wrapper {
    .content {
      font-size: 26rpx;
      color: #666;
      line-height: 1.6;
      width: 100%;
    }
  }
}

.room-list {
  margin-top: 20rpx;
  padding: 0 20rpx 200rpx 20rpx;

  .room-item {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .room-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 16rpx; /* Slightly reduced spacing */
    }

    .room-desc {
      font-size: 26rpx;
      color: #666;
      line-height: 1.6;
      margin-bottom: 24rpx;
    }

    .room-images {
      display: flex;
      flex-direction: column;
      gap: 20rpx;
      margin-bottom: 24rpx;

      .room-image {
        width: 100%;
        height: auto;
        display: block; // Add this line
        border-radius: 12rpx;
        overflow: hidden;
      }
    }

  }
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 100;

  .action-group {
    display: flex;
    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-right: 20rpx;
      .icon {
        font-size: 32rpx;
        margin-bottom: 4rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .favorite-icon {
        width: 40rpx;
        height: 40rpx;
      }
      .count {
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .button-group {
    display: flex;
    gap: 16rpx;

    .contact-btn {
      flex: 1;
      background-color: #e93b3d;
      color: #fff;
      border-radius: 8rpx;
      padding: 16rpx 24rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

/* 图片画廊样式 */
.gallery-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.95);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.gallery-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  touch-action: none;
}

.gallery-fullscreen {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.gallery-image {
  max-width: 100%;
  max-height: 100%;
  transition: transform 0.1s ease-out;
  will-change: transform;
  position: absolute;
}

.gallery-header {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  padding: 40rpx 30rpx 20rpx;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 2;
  background: linear-gradient(to bottom, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%);
}

.gallery-index {
  font-size: 32rpx;
  font-weight: 500;
}

.gallery-actions {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.gallery-action {
  font-size: 28rpx;
  color: white;
  padding: 12rpx 20rpx;
  background: rgba(255,255,255,0.2);
  border-radius: 20rpx;
}

.gallery-close {
  font-size: 44rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255,255,255,0.2);
}

.gallery-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx 40rpx;
  z-index: 2;
  background: linear-gradient(to top, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%);
}

.gallery-dots {
  display: flex;
  justify-content: center;
  gap: 16rpx;
}

.gallery-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background: rgba(255,255,255,0.4);
  transition: all 0.3s ease;

  &.active {
    background: #fff;
    transform: scale(1.2);
  }
}

.gallery-arrows {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  transform: translateY(-50%);
  display: flex;
  justify-content: space-between;
  padding: 0 30rpx;
  z-index: 2;
}

.gallery-arrow {
  font-size: 60rpx;
  color: white;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255,255,255,0.2);
  border-radius: 50%;
  transition: all 0.3s ease;

  &.disabled {
    opacity: 0.3;
    pointer-events: none;
  }

  &:active {
    background: rgba(255,255,255,0.4);
  }
}
</style>

<script>export default {
  data() {
    return {
      isFavorite: false,
      caseInfo: {},
      roomList: [],
      bannerImages: [],
      showGallery: false,
      currentImageIndex: 0,
      currentRoomImageIndex: 0,

      // 手势相关数据
      scale: 1,
      lastScale: 1,
      translateX: 0,
      translateY: 0,
      lastTranslateX: 0,
      lastTranslateY: 0,
      startX: 0,
      startY: 0,
      isDragging: false,
      isScaling: false,
      initialDistance: 0,
      lastTouchTime: 0,
      gallerySource: 'case', // 'case' 或 'room'
      roomImageIndex: 0
    };
  },
  onLoad(options) {
    const sbId = options.sbId;
    console.info("sbId:"+sbId);
    this.queryCaseDetail(sbId);
  },
  computed: {
    currentImage() {
      if (this.gallerySource === 'room') {
        const room = this.roomList[this.roomImageIndex];
        if (room && room.sbiImgs) {
          const images = this.getRoomImages(room.sbiImgs);
          return images[this.currentRoomImageIndex] || images[0];
        }
        return '';
      }
      return this.bannerImages[this.currentImageIndex];
    },
    imageStyle() {
      return {
        transform: `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`,
        transition: this.isDragging || this.isScaling ? 'none' : 'transform 0.2s ease'
      };
    }
  },
  methods: {
    async queryCaseDetail(sbId) {
      var that = this;
      await that.$shopxHttp.httpRequestNoLogin({
        url: '/showBasicCase/queryOneByPrimaryKey',
        submitType: 'POST',
        data: {
          sbId
        },
        successCallback: (res) => {
          that.caseInfo = res.rspData;
          // Process banner images
          that.bannerImages = that.processImageList(that.caseInfo.sbBanner);
          // Process room list
          that.roomList = that.caseInfo.sbimList || [];
          console.info("caseInfo:"+JSON.stringify(that.caseInfo));
        },
        isSucAlert: 'y'
      });
    },

    getRoomImages(imagesString) {
      if (!imagesString) return [];
      return imagesString.split(',').filter(img => img).map(img => this.getFullImageUrl(img));
    },

    // Process comma-separated image list
    processImageList(imageString) {
      if (!imageString) return [];
      return imageString.split(',').filter(img => img).map(img => this.getFullImageUrl(img));
    },

    // Get full image URL with OSS prefix
    getFullImageUrl(imagePath) {
      if (!imagePath) return '/static/default-image.png';
      return this.$ossPath + imagePath;
    },

    // Get first image from comma-separated list
    getFirstImage(imagesString) {
      if (!imagesString) return '';
      const images = imagesString.split(',');
      return images[0] || '';
    },

    toggleFavorite() {
      this.isFavorite = !this.isFavorite;
      uni.showToast({
        title: this.isFavorite ? '已收藏' : '已取消收藏',
        icon: 'success'
      });
    },

    openImageGallery(index) {
      this.gallerySource = 'case';
      this.currentImageIndex = index;
      this.showGallery = true;
      this.resetTransform();
    },

    openRoomImageGallery(roomIndex, imageIndex = 0) {
      this.gallerySource = 'room';
      this.roomImageIndex = roomIndex;
      this.currentRoomImageIndex = imageIndex;
      this.showGallery = true;
      this.resetTransform();
    },

    closeGallery() {
      this.showGallery = false;
      this.resetTransform();
    },

    getCurrentRoomImagesLength() {
      if (this.gallerySource === 'room' && this.roomList[this.roomImageIndex]) {
        return this.getRoomImages(this.roomList[this.roomImageIndex].sbiImgs).length;
      }
      return 0;
    },

    getCurrentRoomImages() {
      if (this.gallerySource === 'room' && this.roomList[this.roomImageIndex]) {
        return this.getRoomImages(this.roomList[this.roomImageIndex].sbiImgs);
      }
      return [];
    },

    prevImage() {
      if (this.gallerySource === 'room') {
        if (this.currentRoomImageIndex > 0) {
          this.currentRoomImageIndex--;
          this.resetTransform();
        }
      } else {
        if (this.currentImageIndex > 0) {
          this.currentImageIndex--;
          this.resetTransform();
        }
      }
    },

    nextImage() {
      if (this.gallerySource === 'room') {
        const currentRoom = this.roomList[this.roomImageIndex];
        const roomImages = currentRoom ? this.getRoomImages(currentRoom.sbiImgs) : [];
        if (this.currentRoomImageIndex < roomImages.length - 1) {
          this.currentRoomImageIndex++;
          this.resetTransform();
        }
      } else {
        if (this.currentImageIndex < this.bannerImages.length - 1) {
          this.currentImageIndex++;
          this.resetTransform();
        }
      }
    },

    switchImage(index) {
      if (this.gallerySource === 'room') {
        this.currentRoomImageIndex = index;
      } else {
        this.currentImageIndex = index;
      }
      this.resetTransform();
    },

    resetTransform() {
      this.scale = 1;
      this.lastScale = 1;
      this.translateX = 0;
      this.translateY = 0;
      this.lastTranslateX = 0;
      this.lastTranslateY = 0;
      this.isDragging = false;
      this.isScaling = false;
    },

    handleImageTap(e) {
      const currentTime = new Date().getTime();
      const timeDiff = currentTime - this.lastTouchTime;

      // 双击检测 (300ms内连续点击)
      if (timeDiff < 300) {
        if (this.scale === 1) {
          // 双击放大到2倍
          this.scale = 2;
          this.lastScale = 2;
        } else {
          // 双击恢复原始大小
          this.resetTransform();
        }
      }

      this.lastTouchTime = currentTime;
    },

    handleTouchStart(e) {
      if (e.touches.length === 1) {
        // 单指触摸 - 拖拽
        this.startX = e.touches[0].clientX;
        this.startY = e.touches[0].clientY;
        this.isDragging = true;

        // 记录开始拖拽时的位置
        this.lastTranslateX = this.translateX;
        this.lastTranslateY = this.translateY;

      } else if (e.touches.length === 2) {
        // 双指触摸 - 缩放
        this.isScaling = true;
        this.handlePinchStart(e);
      }
    },

    handleTouchMove(e) {
      if (e.touches.length === 1 && this.isDragging) {
        // 单指移动 - 拖拽
        const currentX = e.touches[0].clientX;
        const currentY = e.touches[0].clientY;
        const deltaX = currentX - this.startX;
        const deltaY = currentY - this.startY;

        // 只有在缩放状态下才允许拖拽
        if (this.scale > 1) {
          this.translateX = this.lastTranslateX + deltaX;
          this.translateY = this.lastTranslateY + deltaY;

          // 限制拖拽范围，防止图片被拖出可视区域
          this.limitTranslation();
        }

      } else if (e.touches.length === 2 && this.isScaling) {
        // 双指移动 - 缩放
        this.handlePinchMove(e);
      }
    },

    handleTouchEnd(e) {
      if (e.changedTouches.length === 1 && this.isDragging) {
        const endX = e.changedTouches[0].clientX;
        const endY = e.changedTouches[0].clientY;
        const deltaX = endX - this.startX;
        const deltaY = endY - this.startY;

        // 如果是在未缩放状态下水平滑动超过50px，切换图片
        if (this.scale === 1 && Math.abs(deltaX) > 50 && Math.abs(deltaX) > Math.abs(deltaY)) {
          if (deltaX > 0) {
            this.prevImage(); // 向右滑动，显示上一张
          } else {
            this.nextImage(); // 向左滑动，显示下一张
          }
        }

        this.isDragging = false;
      } else if (e.changedTouches.length === 2) {
        this.isScaling = false;
      }
    },

    handlePinchStart(e) {
      // 记录初始距离
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      this.initialDistance = Math.sqrt(
          Math.pow(touch1.clientX - touch2.clientX, 2) +
          Math.pow(touch1.clientY - touch2.clientY, 2)
      );
      this.lastScale = this.scale;

      // 记录缩放中心点，用于调整平移
      this.scaleCenterX = (touch1.clientX + touch2.clientX) / 2;
      this.scaleCenterY = (touch1.clientY + touch2.clientY) / 2;
      this.lastTranslateX = this.translateX;
      this.lastTranslateY = this.translateY;
    },

    handlePinchMove(e) {
      // 计算当前距离
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      const currentDistance = Math.sqrt(
          Math.pow(touch1.clientX - touch2.clientX, 2) +
          Math.pow(touch1.clientY - touch2.clientY, 2)
      );

      // 计算缩放比例
      const scaleRatio = currentDistance / this.initialDistance;
      const newScale = this.lastScale * scaleRatio;

      // 限制缩放范围
      this.scale = Math.max(0.5, Math.min(5, newScale));

      // 计算缩放中心点
      const currentCenterX = (touch1.clientX + touch2.clientX) / 2;
      const currentCenterY = (touch1.clientY + touch2.clientY) / 2;

      // 调整平移，使缩放中心保持稳定
      const scaleChange = this.scale - this.lastScale;
      this.translateX = this.lastTranslateX + (currentCenterX - this.scaleCenterX) * scaleChange * 0.5;
      this.translateY = this.lastTranslateY + (currentCenterY - this.scaleCenterY) * scaleChange * 0.5;

      // 限制拖拽范围
      this.limitTranslation();
    },

    limitTranslation() {
      // 根据缩放比例计算最大平移范围
      // 缩放越大，允许的平移范围也越大
      const maxTranslate = (this.scale - 1) * 100;

      this.translateX = Math.max(-maxTranslate, Math.min(maxTranslate, this.translateX));
      this.translateY = Math.max(-maxTranslate, Math.min(maxTranslate, this.translateY));
    },

    contactDesigner() {
      uni.showToast({
        title: '正在联系设计师...',
        icon: 'loading'
      });
    },

    getScheme() {
      uni.showToast({
        title: '方案已发送至您的邮箱',
        icon: 'success'
      });
    }
  }
};
</script>